package cn.kgc.ssm.service.impl;

import cn.kgc.ssm.dto.TbAddressPageDTO;
import cn.kgc.ssm.entity.TbAddress;
import cn.kgc.ssm.mapper.TbAddressMapper;
import cn.kgc.ssm.service.TbAddressService;
import cn.kgc.ssm.utils.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: hengge
 * @version: v1.0
 * @DATE: 2022/10/22
 */
@Service
public class TbAddressServiceImpl implements TbAddressService {
    @Autowired
    private TbAddressMapper tbAddressMapper;

    //1.查询所有和条件(搜索功能)查询
    @Override
    public Result search(TbAddressPageDTO userPageDTO) {
        Result result = new Result();

        try {
            //使用分页插件是实现分页信息
            //userPageDTO.getPage():当前页  userPageDTO.getLimit():当前页显示的数据
            PageHelper.startPage(userPageDTO.getPage(), userPageDTO.getLimit());
            List<TbAddress> users = tbAddressMapper.search(userPageDTO.getAddId());
            //获取更加详细的分页信息
            PageInfo<TbAddress> userPageInfo = new PageInfo<>(users);
            //获取总条数
            long total = userPageInfo.getTotal();

            //封装返回数据
            result.setCode(0);
            result.setMsg("查询成功");
            result.setCount(total);
            result.setData(users);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("查询失败");
        }

        return result;
    }

    //2.添加用户信息
    @Override
    public Result add(TbAddress tbAddress) {
        Result result = new Result();

        try {
            tbAddressMapper.add(tbAddress);
            result.setCode(0);
            result.setMsg("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("添加失败");
        }
        return result;
    }

    //3.编辑用户信息
    @Override
    public Result update(TbAddress tbAddress) {
        Result result = new Result();

        try {
            tbAddressMapper.update(tbAddress);
            result.setCode(0);
            result.setMsg("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("更新失败");
        }
        return result;
    }

    //4.删除或批量删除用户信息
    @Override
    public Result deleteMore(String[] idArray) {
        Result result = new Result();
        try {
            tbAddressMapper.deleteMore(idArray);
            result.setCode(0);
            result.setMsg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMsg("删除失败");
        }
        return result;
    }

}
